﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CMS.Domain.Services
{
    public class PublishService
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="relativeHtmlDirectory"></param>
        /// <param name="htmlDirectory">发布之后文件存储的目录</param>
        /// <param name="templateFile">模板文件地址</param>
        /// <param name="displayPublishedTime">显示的发布时间</param>
        /// <returns></returns>
        public CPPEI.ServiceResult PublishArticle(Guid id, string relativeHtmlDirectory, string htmlDirectory, string templateFile, DateTime? displayPublishedTime)
        {
            using(CMSDbContext dbContext = new CMSDbContext())
            {
                EntityRepository<Entities.EArticle> rep = new EntityRepository<Entities.EArticle>(dbContext);

                Entities.EArticle article = rep.Get(p => p.Id == id);
                if(article == null)
                {
                    return new CPPEI.ServiceResult(0);
                }

                if(article.IsEnabled == false)
                {
                    return new CPPEI.ServiceResult(1);
                }

                string htmlFile = string.Format("{0}{1}{2:d5}.html", htmlDirectory, article.CreatedTime.ToString("yyyyMMdd"), article.Number);
                string htmlUrl = string.Format("{0}{1}{2:d5}.html", relativeHtmlDirectory, article.CreatedTime.ToString("yyyyMMdd"), article.Number);

                article.PublishedTime = DateTime.Now;
                article.PublishedUrl = htmlUrl;
                article.PublishedFile = htmlFile;
                if(displayPublishedTime !=null)
                {
                    article.DisplayPublishedTime = displayPublishedTime.Value;
                }
                else
                {
                    article.DisplayPublishedTime = article.PublishedTime.Value;
                }

                HtmlPublisher.Instance.Push(article, htmlFile, templateFile);

                rep.Update(article);
                try
                {
                    dbContext.SaveChanges();

                    return new CPPEI.ServiceResult();
                }
                catch(Exception ex)
                {

                    return new CPPEI.ServiceResult(0);
                }
            }
        }
    }
}
